package server;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;

import common.exceptions.ConfigurationException;
import common.interfaces.IClient;

import server.interfaces.IAuthenticationProvider;

// TODO dokumentacja
public class SimpleAuthenticationProvider implements IAuthenticationProvider {

	public static final Logger LOG = Logger.getLogger(SimpleAuthenticationProvider.class); 
	
	/**
	 * @uml.property  name="clients"
	 * @uml.associationEnd  qualifier="key:java.lang.Object java.lang.String"
	 */
	private Map<String, String> clients = new HashMap<String, String>();

	public void configure(Properties properties){
		
		String fileName = properties.getProperty("server.userFile");
		
		try {

			if( fileName == null ) throw new ConfigurationException("User file must be suplied for SimpleAuthenticationProvider");
			
			BufferedReader br = new BufferedReader( new InputStreamReader( new FileInputStream( fileName ) ) );
			int lineNo = 0;
			String line = null;
			
			while( (line = br.readLine()) != null ){
				lineNo++;
				String[] contents = line.split(";");
				if( contents.length == 2 ){
					if( clients.containsKey(contents[0]) ){
						clients.put(contents[0], contents[1]);
						LOG.info("Updated user data for user '" + contents[0] + "'" );						
					}else{
						clients.put(contents[0], contents[1]);
						LOG.info("Added user '" + contents[0] + "' to user database" );						
					}

				}else{
					LOG.error("Error while processing user file: '" + fileName + "' at line: " + lineNo);
				}
			}
		} catch (FileNotFoundException e) {
			LOG.error("Couldn't load user file: '" + fileName + "'");
		} catch (IOException e) {
			LOG.error("Error parsing user file: '" + fileName + "'");
		} catch (ConfigurationException e) {
			LOG.error(e.message);
		}
		
	}

	/* (non-Javadoc)
	 * @see server.IAuthenticationProvider#clientExists(server.comm.IClient)
	 */
	public boolean clientExists( IClient client){
		return clients.containsKey(client.getUserName());
	}
	
	/* (non-Javadoc)
	 * @see server.IAuthenticationProvider#authenticateClient(server.comm.IClient, java.lang.String)
	 */
	public boolean authenticateClient( IClient client, String password){
		return clients.containsKey(client.getUserName()) 
			? clients.get(client.getUserName()).equals(password) 
			: true;
	}
	
}
